package com.icinfo.cloud.provider.punish.simple.transfer.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.icinfo.cloud.common.core.page.PageResponse;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.DateUtil;
import com.icinfo.cloud.provider.punish.common.publicsecurityentrust.service.MemberApiService;
import com.icinfo.cloud.provider.punish.common.publicsecurityentrust.vo.MemberDeptVo;
import com.icinfo.cloud.provider.punish.common.publicsecurityentrust.vo.MemberOrgVo;
import com.icinfo.cloud.provider.punish.simple.transfer.dto.CaseSimpleTransferRecordPageDto;
import com.icinfo.cloud.provider.punish.simple.transfer.mapper.CaseSimpleTransferRecordMapper;
import com.icinfo.cloud.provider.punish.simple.transfer.model.CaseSimpleTransferRecord;
import com.icinfo.cloud.provider.punish.simple.transfer.service.ICaseSimpleTransferRecordService;
import com.icinfo.cloud.provider.punish.simple.transfer.vo.CaseSimpleTransferRecordPageVo;
import com.icinfo.cloud.provider.punish.simple.transfer.vo.CaseSimpleTransferRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author HKxxx
 * @date 2024/2/1 13:55
 */
@Service
@Slf4j
public class CaseSimpleTransferRecordServiceImpl extends MyBatisServiceSupport implements ICaseSimpleTransferRecordService {

    @Resource
    private CaseSimpleTransferRecordMapper caseSimpleTransferRecordMapper;
    @Resource
    private MemberApiService memberApiService;

    @Resource
    private ICaseMainInfoService caseMainInfoService;


    @Override
    public PageResponse<CaseSimpleTransferRecordPageVo> pageList(CaseSimpleTransferRecordPageDto dto) {
        UserDTO user = getUser();
        PageHelper.startPage(dto.getPageNum(), dto.getLength());
        Example example = new Example(CaseSimpleTransferRecord.class);
        // 设置查询参数
        assemblyParameter(dto, user, example);
        List<CaseSimpleTransferRecord> transferRecords = caseSimpleTransferRecordMapper.selectByExample(example);
        if (CollUtil.isEmpty(transferRecords)) {
            return PageResponse.empty();
        }
        // 单位名称信息
        Map<String, MemberOrgVo> orgVos = getOrgVoList(transferRecords);
        // 部门名称信息
        Map<String, MemberDeptVo> deptVos = getDeptVoList(transferRecords);
        PageResponse<CaseSimpleTransferRecord> pageResponse = new PageResponse<>(transferRecords);
        return pageResponse.convert(info -> CaseSimpleTransferRecordPageVo.convertPageVo(info, orgVos, deptVos));
    }

    private Map<String, MemberDeptVo> getDeptVoList(List<CaseSimpleTransferRecord> transferRecords) {
        List<String> deptCodes = new ArrayList<>();
        List<String> entrustDeptCodes = transferRecords.stream().map(CaseSimpleTransferRecord::getEntrustDeptCode).filter(StrUtil::isNotBlank).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(entrustDeptCodes)) {
            deptCodes.addAll(entrustDeptCodes);
        }
        List<String> handleDeptCodes = transferRecords.stream().map(CaseSimpleTransferRecord::getHandleDeptCode).filter(StrUtil::isNotBlank).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(handleDeptCodes)) {
            deptCodes.addAll(handleDeptCodes);
        }
        return memberApiService.getDeptNameByDeptCode(deptCodes);
    }

    private Map<String, MemberOrgVo> getOrgVoList(List<CaseSimpleTransferRecord> transferRecords) {
        List<String> orgCodes = new ArrayList<>();
        List<String> handleOrgCodes = transferRecords.stream().map(CaseSimpleTransferRecord::getHandleOrgCode).filter(StrUtil::isNotBlank).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(handleOrgCodes)) {
            orgCodes.addAll(handleOrgCodes);
        }
        return memberApiService.getOrgNameByOrgCode(orgCodes);
    }

    private void assemblyParameter(CaseSimpleTransferRecordPageDto dto, UserDTO user, Example example) {
        Example.Criteria criteria = example.createCriteria();
        // 当事人
        if (StrUtil.isNotBlank(dto.getPartyName())) {
            criteria.andLike("partyName", "%" + dto.getPartyName() + "%");
        }
        // 当事人类型
        if (StrUtil.isNotBlank(dto.getPartyType())) {
            criteria.andEqualTo("partyType", dto.getPartyType());
        }
        // 主办人
        if (StrUtil.isNotBlank(dto.getMainHandlePerson())) {
            criteria.andLike("mainHandlePerson", "%" + dto.getMainHandlePerson() + "%");
        }
        // 日期范围
        if (!Objects.isNull(dto.getStartTime()) && !Objects.isNull(dto.getEndTime())) {
            criteria.andBetween("createTime", DateUtil.getStartTime(dto.getStartTime()), DateUtil.getEndTime(dto.getEndTime()));
        }
        // 查询范围
        if (Constant.STRING_1.equals(dto.getEnforceRegiLevel())) {
            //重庆查询全市数据时，不用调用接口，根据当前用户区划前两位模糊查询即可
            criteria.andLike("handleAreaCode", "%" + user.getAreaCode().substring(0, 2) + "%");
        } else if (Constant.STRING_4.equals(dto.getEnforceRegiLevel())) {
            // 街道查询，只需要使用当前用户的orgCode 精准匹配
            criteria.andEqualTo("handleOrgCode", user.getOrgCode());
        } else {
            // 其余如区县查询，则查询当前用户的areaCode与下级编码
            List<String> areaCodes = caseMainInfoService.limitArea(user.getAreaCode());
            criteria.andIn("handleAreaCode", areaCodes);
        }
    }

    @Override
    public CaseSimpleTransferRecordVo details(String id) {
        if (StrUtil.isBlank(id)) {
            throw new BusinessException("移交id不能为空！");
        }
        CaseSimpleTransferRecord record = caseSimpleTransferRecordMapper.selectByPrimaryKey(id);
        if (Objects.isNull(record)) {
            throw new BusinessException("无对应的移交详情");
        }
        // 查询办案部门名称
        Map<String, MemberOrgVo> orgVos = memberApiService.getOrgNameByOrgCode(Collections.singletonList(record.getHandleOrgCode()));
        List<String> deptCodes = new ArrayList<>();
        if (StrUtil.isNotBlank(record.getEntrustDeptCode())) {
            deptCodes.add(record.getEntrustDeptCode());
        }
        if (StrUtil.isNotBlank(record.getHandleDeptCode())) {
            deptCodes.add(record.getHandleDeptCode());
        }
        Map<String, MemberDeptVo> deptVos = memberApiService.getDeptNameByDeptCode(deptCodes);
        return CaseSimpleTransferRecordVo.convertRecordVo(record, orgVos, deptVos);
    }


}
